package com.mocne.Common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBC_sql_handle {

    public JDBC_sql_handle(String sql) {
        try {
            Connection con = null; //定义一个MYSQL链接对象
            Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL驱动
            con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mocne_test", "root", "kaifeng0605."); //链接本地MYSQL

            Statement stmt; //创建声明
            stmt = con.createStatement();

            if (sql.startsWith("SELECT")) {
                //查询数据并输出
                ResultSet selectRes = stmt.executeQuery(sql);
                while (selectRes.next()) { //循环输出结果集
                    String username = selectRes.getString("username");
                    String password = selectRes.getString("password");
                    System.out.print("\r\n\r\n");
                    System.out.print("username: " + username + "; password: " + password);
                }
            } else if (sql.startsWith("INSERT")) {
                //新增一条数据
                stmt.executeUpdate(sql);
                ResultSet res = stmt.executeQuery("select LAST_INSERT_ID()");
                int ret_id;
                if (res.next()) {
                    ret_id = res.getInt(1);
                    System.out.print(ret_id);
                }
            } else if (sql.startsWith("DELETE")) {
                //删除一条数据
                long deleteRes = stmt.executeUpdate(sql); //如果为0则没有进行删除操作，如果大于0，则记录删除的条数
                System.out.print("DELETE: " + deleteRes);
            } else if (sql.startsWith("UPDATE")) {
                //更新一条数据
                long updateRes = stmt.executeUpdate(sql);
                System.out.print("UPDATE: " + updateRes);
            } else {
                System.out.print("unKnownSql: " + sql);
            }
        } catch (Exception e) {
            System.out.print("MYSQL ERROR:" + e.getMessage());
        }

    }

    @SuppressWarnings("unused")
	public static void main(String[] args){
        JDBC_sql_handle aaa = new JDBC_sql_handle("SELECT name from xTestDemo where id = 1;");
    }
}
